<template>
  <div class="createPost-container">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="150px">
      <el-form-item label="游戏平台" prop="gamePlatformId">
        <el-select v-model="form.gamePlatformId">
          <el-option
            v-for="item in GAME_PLATFORM_LIST.filter((item)=>{return item.type.includes('noticeOrderData')})"
            :key="item.value"
            :label="item.title"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="处理日期" prop="dealDate">
        <el-date-picker
          v-model="form.dealDate"
          align="center"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="跳过报表头">
        <el-select v-model="form.reportSkipHeader">
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="注单号所在列">
        <el-input maxlength="15" v-model="form.reportBetIdCols"></el-input>
      </el-form-item>
      <el-form-item label="有效投注金额所在列">
        <el-input maxlength="15" v-model="form.reportBetAmountCols"></el-input>
      </el-form-item>
      <el-form-item label="输赢所在列">
        <el-input maxlength="15" v-model="form.reportBetWinlossCols"></el-input>
      </el-form-item>
      <el-form-item label="查询时间" prop="time">
        <el-date-picker
          v-model="form.time"
          class="filter-item"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :picker-options="pickerWeekStep"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          align="center">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上传文件" prop="fileList">
        <el-upload
          :multiple="true"
          ref="upload"
          :limit="limit"
          action="/api/gl/game/history/comparison/createJob"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
          :on-change="handleChange"
          :on-error="handleFail"
          :headers="header"
          :data="formData"
          :file-list="form.fileList"
          :on-exceed="handleExceed"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary" icon='el-icon-upload'>选取文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="上传文件编码">
        <el-input maxlength="20" v-model="form.charsetName"></el-input>
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button type="primary" @click="save">确定</el-button>
      <el-button @click="$emit('callBack', false)">取消</el-button>
    </div>
  </div>
</template>

<script>
import md5 from 'blueimp-md5';
import { form, pickerOption } from '@/build';
import { GAME_PLATFORM_LIST } from '../data';
import { getLogin } from '@/utils/auth';
import {
  addNoticeData as saveData,
} from '@/services/api/gameDataManage';

export default {
  name: 'addNoticeData',
  mixins: [form, pickerOption],
  data() {
    return {
      GAME_PLATFORM_LIST,
      form: {
        gamePlatformId: undefined,
        dealDate: undefined,
        reportSkipHeader: undefined,
        reportBetIdCols: undefined,
        reportBetAmountCols: undefined,
        reportBetWinlossCols: undefined,
        time: undefined,
        fileList: [],
        charsetName: undefined,
      },
      // signForTime: '', // 用于标记查询时间字段是否需要验证
      // signForFile: '', // 用于标记上传文件字段是否需要验证
      limit: 1,
      rules: {
        gamePlatformId: [
          {
            required: true,
            message: '请选择游戏平台',
          },
        ],
        dealDate: [
          {
            required: true,
            message: '请选择处理日期',
          },
        ],
        // time: [
        //   {
        //     required: true,
        //     message: '请选择查询时间',
        //   },
        // ],
        // fileList: [
        //   {
        //     required: true,
        //     message: '请上传文件',
        //   },
        // ],
      },
    };
  },
  computed: {
    header() {
      return this._addSign();
    },
    formData() {
      const tempForm = {};
      Object.keys(this.form).forEach((key) => {
        if (this.form[key] && this.form[key] !== 0) {
          tempForm[key] = this.form[key];
        }
      });
      const { time } = tempForm;
      let httpQueryStartTime; let httpQueryEndTime;
      if (!_.isUndefined(time) && _.isArray(time)) {
        httpQueryStartTime = time[0];
        httpQueryEndTime = time[1];
      }
      if (tempForm.dealDate) {
        tempForm.dealDate += ' 00:00:00';
      }
      delete tempForm.time; // 删除不需要的参数
      return httpQueryStartTime ? { ...tempForm, httpQueryStartTime, httpQueryEndTime } : tempForm;
    },
  },
  watch: {
    // 'form.time': {
    //   handler(newVal) {
    //     if (!_.isEmpty(newVal)) {
    //       this.signForFile = 'yes';
    //     } else {
    //       this.signForFile = '';
    //     }
    //   },
    // },
    // 'form.fileList': {
    //   handler(newVal) {
    //     this.$refs.ruleForm.validateField('fileList');
    //     if (!_.isEmpty(newVal)) {
    //       this.signForTime = 'yes';
    //     } else {
    //       this.signForTime = '';
    //     }
    //   },
    // },
  },
  methods: {
    handleSuccess(response, file) {
      if (response.code === 1) {
        this.$emit('callBack', true);
        this.$message({
          type: 'success',
          message: '保存成功',
        });
      } else {
        this.$notify.error(response.message);
      }
    },
    handleFail(err) {
      this.$message({
        type: 'error',
        message: err,
      });
    },
    _addSign() {
      const timestamp = Date.parse(new Date());
      const signParams = {};
      const { token, uid } = getLogin();
      signParams.device_id = '1.0';
      signParams.os_type = 0;
      signParams.timestamp = timestamp;
      signParams.version = '1.0';
      const urlStr = this.urlEncode(signParams).substr(1);
      signParams.token = token;
      signParams.uid = uid;
      signParams.sign = md5(`${urlStr}global`);
      // console.log(urlStr)

      return signParams;
    },
    urlEncode(param, key, encode) {
      if (param == null) return '';
      let paramStr = '';
      const t = typeof (param);
      if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += `&${key}=${(encode == null || encode) ? encodeURIComponent(param) : param}`;
      } else {
        for (const i in param) {
          const k = key == null ? i : key + (param instanceof Array ? `[${i}]` : `.${i}`);
          paramStr += this.urlEncode(param[i], k, encode);
        }
      }
      return paramStr;
    },
    handleExceed() {
      this.$notify.error(`文件数量超出限制，最多上传${this.limit}个`);
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!');
      }
    },
    handleChange(file, fileList) {
      this.form.fileList = fileList;
    },
    save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.fileList.length > 0) {
            this.$refs.upload.submit();
          } else {
            this.doSave({ action: 'addNoticeData', form: 'ruleForm' });
          }
        } else {
          return false;
        }
      });
    },
  },
  mounted() {
    this.bindSave(saveData, 'addNoticeData', 'form', {
      beforeSend: (data) => {
        const { time } = data;
        let { dealDate } = data;
        let httpQueryStartTime; let httpQueryEndTime;
        if (!_.isUndefined(time) && _.isArray(time)) {
          httpQueryStartTime = time[0];
          httpQueryEndTime = time[1];
        }
        if (dealDate) {
          dealDate += ' 00:00:00';
        }
        return {
          ...data,
          httpQueryStartTime,
          httpQueryEndTime,
          dealDate,
        };
      },
      afterSuccess: (([result, data]) => {
        if (result) {
          this.$emit('callBack', true);
        }
      }),
    });
  },
};
</script>

<style scoped lang="scss">
.footer{
  text-align: right;
}
/deep/ {
  .el-form-item{
    .el-form-item__content{
      width:calc(90% - 150px);
      .el-select{
        width: 100%;
      }
      .el-date-editor{
        width:100%;
      }
    }
  }
}
</style>
